/*LICENSE_BEGIN
 * ******************************************************************
 * Copyright 2006 by the Dainamite Robocup-Team at the
 * DAI-Labor, TU-Berlin (www.dai-labor.de)
 * 
 * Members of Dainamite are:
 * Holger Endert
 * Robert Wetzker
 * Thomas Karbe
 * Axel Heßler
 * Philippe Bütter
 * Felix Brossmann
 * 
 * Licensed under the GNU GPL (General Public License) Free Software 
 * License, Version 2. You may use this file only in compliance with 
 * the License. You may obtain a copy of the License at:
 * 
 * http://www.fsf.org/licensing/licenses/gpl.txt
 * ******************************************************************
LICENSE_END*/
package robocup.connection;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;


/**
 * This class is used to buffer data, which is send and received when 
 * communicating with the soccer server. Since the data is always passed as
 * string, this class provides the corresponding methods for setting and
 * getting these.
 */
public class ByteBuffer extends ByteArrayOutputStream {

	/**
	 * A class that is capable of storing data
	 * 
	 * @param size -
	 *            the size of the buffer
	 */
	public ByteBuffer(int size) {
		super(size);
	}

	/**
	 * @return returns the buffer-array.
	 */
	public byte[] getByteArray() {
		return this.buf;
	}

	/**
	 * This methdo sets a string into the buffer.
	 * @param str - the string to set.
	 * @throws IOException
	 */
	public synchronized void setString(String str) throws IOException {
		super.write(str.getBytes());
	}

	/**
	 * @return string containing the buffered data.
	 * @throws IOException
	 */
	public String getString() throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(this.buf);
		int c;
		StringWriter w = new StringWriter();
		while (((c = in.read()) != 0) && (c != -1)) {
			w.write((char) c);
		}
		return w.getBuffer().toString();
	}

	/**
	 * @return The length of the buffer-array.
	 */
	public int length() {
		return this.buf.length;
	}

	/**
	 * Resets all values of the buffer-array to zero.
	 */
	@Override
	public void reset() {
		super.reset();

		for (int i = 0; i < this.buf.length; i++)
			write(0);
		super.reset();
	}
}
